package com.xzr.hospitalregister.activity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.xzr.hospitalregister.R;
import com.xzr.hospitalregister.base.BaseActivity;
import com.xzr.hospitalregister.entity.CallNumberListItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;

import static com.xzr.hospitalregister.R.id.input_text;


/**
 * Created by Administrator on 2018/1/24 0024.
 */

public class SpeechActivity extends BaseActivity implements TextToSpeech.OnInitListener,TextToSpeech.OnUtteranceCompletedListener{
    private EditText input;
    private Button speech;//,record

    private TextToSpeech textToSpeech;
    private TextView tv_yuyin,text1;

    private static final int msgKey2 = 5;//////////////////
    public boolean isSelected = true;////////////////
    private static final String fileName = "sharedfile";//定义保存的文件的名称

    private List<CallNumberListItem> data = new ArrayList<>();
    private MediaPlayer music = null;// 播放器引用
    private int lastUtterance = -1;
    private String[] loveArray;
    private HashMap<String, String> params = new HashMap<String, String>();
    private static final String STORE_NAME = "preferenceFile";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        getSupportActionBar().hide();// 隐藏ActionBar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//remove notification bar  即全屏
        setContentView(R.layout.activity_speech);
//        if(isSelected){
//        textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
//            @Override
//            public void onInit(int status) {
//                if (status == textToSpeech.SUCCESS) {
//                    int result = textToSpeech.setLanguage(Locale.CHINA);
//                    if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE
//                            && result != TextToSpeech.LANG_AVAILABLE) {
//                        Toast.makeText(SpeechActivity.this, "TTS暂时不支持这种语音的朗读！",
//                                Toast.LENGTH_SHORT).show();
//                    }
//                }
//            }
//        });
        ////////////
        textToSpeech = new TextToSpeech(this,
                this  // TextToSpeech.OnInitListener
        );
//        SharedPreferences settings = getSharedPreferences(STORE_NAME, 0);
//        lastUtterance = settings.getInt("lastUtterance", -1);
//        Log.v("TAG", "the restored lastUtterance is " + lastUtterance);
//        Log.v("TAG", "上面保存的值 lastUtterance is " + lastUtterance);
//    }//////////
//        deviceId = SystemPropertiesInvoker.get(context, "persist.sys.hwconfig.stb_id");
        new TimeThreadjh().start();////////////////////////////////////////////////////////////////////
        //////////

        input = (EditText) findViewById(input_text);
        speech = (Button) findViewById(R.id.speech);
        tv_yuyin = (TextView) findViewById(R.id.tv_yuyin);
        text1 = (TextView) findViewById(R.id.text1);
//        record = (Button) findViewById(R.id.record);

        speech.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                textToSpeech.speak(input.getText().toString(),
//                        TextToSpeech.QUEUE_ADD, null);
//                textToSpeech.speak(tv_yuyin.getText().toString(),
//                        TextToSpeech.QUEUE_ADD, null);///////////////////////////////
            }
        });

//        record.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                String inputText = input.getText().toString();
//                HashMap<String, String> myHashRender = new HashMap<>();
//                myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, inputText);
//                textToSpeech.synthesizeToFile(inputText, myHashRender,
//                        "/mnt/sdcard/my_recorder_audios/sound.wav");
//                Toast.makeText(SpeechActivity.this, "声音记录成功。", Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    @Override
    protected void onDestroy() {
        if (textToSpeech != null)
            textToSpeech.shutdown();
        super.onDestroy();
    }

    /////////
    public class TimeThreadjh extends Thread {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(10000);
                    Message msg = new Message();
                    msg.what = msgKey2;
                    mHandlerjh.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    private String remberName = null;
    private Handler mHandlerjh = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case msgKey2:
//                    long sysTime = System.currentTimeMillis();
//                    CharSequence sysTimeStr = DateFormat.format("EEEE HH:mm:ss", sysTime);
//                    tv_mTime.setText(sysTimeStr);
//                    //////////
//                    SharedPreferences preferences2 = getSharedPreferences("config", 0);
//                    //////////
//                    if(preferences2.getString("name","").equals(input.getText().toString())){
//                        Log.e("TAG","输入框的内容-----------"+preferences2.getString("name",""));
//                        textToSpeech.stop();
////                        textToSpeech.shutdown();QUEUE_ADD
//                        }else {
//                        for (int i = 0; i <=2 ; i++) {
//                            textToSpeech.speak(input.getText().toString(),
//                                    TextToSpeech.QUEUE_ADD, null);
//                        }
//
//
//                        /////////////
//                        //1,实例化SharedPreferences对象,参数1:保存的名字,参数2:保存的模式MODE_PRIVATE私有的
//                        SharedPreferences preferences = getSharedPreferences("config", MODE_PRIVATE);
//                        //2,让SharedPreferences处于可编辑状态
//                        SharedPreferences.Editor editor = preferences.edit();
//                        Log.e("TAG","输入框的内容+++++++++"+input.getText().toString());
//                        String yddz = input.getText().toString();
//                        //3,储存数据,类似于map
//                        editor.putString("name", yddz);
//                        editor.commit();//提交
//                        }
//                    //////////
                    //////////
//                    String dz = "王五";
//                    String hj ="李四";
//                    String jz = "张三";
//                    List<String> list = new ArrayList<String>();
//                    list.add("请"+hj+"到1诊室就诊"+dz+"准备就诊");
//                    list.add("李四");
//                    list.add("张三");
//                    for(int i = 0;i < list.size(); i ++){
//                        System.out.println(list.get(i));
//                        if(!TextUtils.isEmpty(hj)){
//                            textToSpeech.speak(list.get(i),
//                                    TextToSpeech.QUEUE_ADD, null);
//                        }
//                    }
                    /////////////{"rows":[{"HJ":"张三","ROOMNAME":"1诊室","NAME":"儿童保健部-排队","JZ":"","DOCTCODE":"000027","ROOMCODE":"1","DZ":"赵留"},{"HJ":"李四","ROOMNAME":"1诊室","NAME":"儿童保健部-排队","JZ":"","DOCTCODE":"000027","ROOMCODE":"1","DZ":"王五"},{"HJ":"赵六","ROOMNAME":"1诊室","NAME":"儿童保健部-排队","JZ":"","DOCTCODE":"000027","ROOMCODE":"1","DZ":"李积极"}]}
                    String json = "{\"rows\":[{\"HJ\":\"张三\",\"ROOMNAME\":\"1诊室\",\"NAME\":\"儿童保健部-排队\",\"JZ\":\"\",\"DOCTCODE\":\"000027\",\"ROOMCODE\":\"1\",\"DZ\":\"赵留\"},{\"HJ\":\"李四\",\"ROOMNAME\":\"1诊室\",\"NAME\":\"儿童保健部-排队\",\"JZ\":\"\",\"DOCTCODE\":\"000027\",\"ROOMCODE\":\"1\",\"DZ\":\"王五\"},{\"HJ\":\"赵六\",\"ROOMNAME\":\"1诊室\",\"NAME\":\"儿童保健部-排队\",\"JZ\":\"\",\"DOCTCODE\":\"000027\",\"ROOMCODE\":\"1\",\"DZ\":\"李积极\"}]}";
//                    String json = "{\"rows\":[{\"HJ\":\"张三\",\"ROOMNAME\":\"1诊室\",\"NAME\":\"儿童保健部-排队\",\"JZ\":\"\",\"DOCTCODE\":\"000027\",\"ROOMCODE\":\"1\",\"DZ\":\"赵留\"}]}";
                    try {
                        JSONObject jsonObject = new JSONObject((json));
                        JSONArray jsonData = jsonObject.getJSONArray("rows");
                        for (int i = 0; i < jsonData.length(); i++) {
                            JSONObject jsonObject1 = jsonData.getJSONObject(i);
//                            Log.e("TAG", "json里面的数据+++" + jsonObject1);
                            ///////////
                            data.add(new CallNumberListItem(jsonObject1.getString("ROOMNAME"), jsonObject1.getString("DZ"), jsonObject1.getString("HJ"), jsonObject1.getString("JZ")));
//                            Log.e("TAG", "将请求到的数据添加到集合中+++" + data);
//                            ////////////
//                            for (int j = 0; j < data.size(); j++) {
//                                boolean hasData=false;
//                                if (data.get(j).getHujiao().equals(jsonObject1.getString("HJ"))
//                                        &&data.get(j).getZhunbei().equals(jsonObject1.getString("DZ"))
//                                        &&data.get(j).getZhenshi().equals(jsonObject1.getString("ROOMNAME"))){
//                                    hasData=true;
//                                }
//                                if (!hasData){
//                                    data.add(new CallNumberListItem(jsonObject1.getString("ROOMNAME"), jsonObject1.getString("DZ"), jsonObject1.getString("HJ"), jsonObject1.getString("JZ")));
////                                    Log.e("TAG", "将请求到的数据添加到集合中---" + data);
//                                }
//                                Log.e("TAG", "集合中有值的情况下所显示的值转换成滚动条+++" + "请，" + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊，" + data.get(j).getZhunbei() + "准备就诊");
//                            }
//                            System.out.println(data);
//                            data.clear();
                        }
                        if (data.size() > 0) {
                            // TODO: 2018/2/5 0005 即有待读数据时，启动读音服务
//                            textToSpeech.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() {
//                                @Override
//                                public void onUtteranceCompleted(String utteranceId) {
//                                    Log.e("TAG  Completed :",utteranceId);
//                                }
//                            });
//                            textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
//                                @Override
//                                public void onStart(String utteranceId) {
//                                    Log.e("TAG   onStart :",utteranceId);
//                                }
//
//                                @Override
//                                public void onDone(String utteranceId) {
//                                    Log.e("TAG    onDone  :",utteranceId);
//                                }
//
//                                @Override
//                                public void onError(String utteranceId) {
//
//                                }
//                            });
                            for (int j = 0; j < data.size();j++) {//////////////////////////////
//
//                                /////////////////
                                if (!TextUtils.isEmpty(data.get(j).getHujiao())) {
                                    text1.setText("请," + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊," + data.get(j).getZhunbei() + "准备就诊.");///
                                    Log.e("TAG", "滚动条+++" + "请," + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊," + data.get(j).getZhunbei() + "准备就诊.");
                                    PlayMusic(R.raw.yuyin);
//                                    textToSpeech.speak("请," + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊," + data.get(j).getZhunbei() + "准备就诊.",
//                                        TextToSpeech.QUEUE_ADD, null);
                                    /////////////
                                    //处理输入框里的内容
                                    StringTokenizer loveTokens = new StringTokenizer("请," + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊," + data.get(j).getZhunbei() + "准备就诊.",".");
                                    Log.e("TAG","输入框的内容+++++++++"+"请," + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊," + data.get(j).getZhunbei() + "准备就诊.");
                                    text1.setText("请," + data.get(j).getHujiao() + "到" + data.get(j).getZhenshi() + "就诊," + data.get(j).getZhunbei() + "准备就诊.");///
                                    int i = 0;
                                    loveArray = new String[loveTokens.countTokens()];
                                    while(loveTokens.hasMoreTokens())
                                    {
                                        loveArray[i++] = loveTokens.nextToken();
                                    }
                                    //朗读输入框里的内容
                                    speakText();
//                                    ////////////
//                                    //保存lastUtterance值
//                                    SharedPreferences settings = getSharedPreferences(STORE_NAME, 0);
//                                    SharedPreferences.Editor editor = settings.edit();
//                                    editor.putInt("lastUtterance", lastUtterance);
//                                    editor.commit();
//                                    Log.v("TAG", "the stored lastUtterance is " + lastUtterance);
//                                    //////////////

                                }//////////////////////////////////////////////////////
//                                ////////////////////
//                            ///
//                            Log.e("TAG","获取当前时间"+System.currentTimeMillis());
////                            for (int j = 0; j < data.size(); j++) {
//                                Log.e("TAG", "集合中有值的情况下所显示的值转换成滚动条+++" + "请，" + data.get(0).getHujiao() + "到" + data.get(0).getZhenshi() + "就诊，" + data.get(0).getZhunbei() + "准备就诊");
//                                text1.setText("请，" + data.get(0).getHujiao() + "到" + data.get(0).getZhenshi() + "就诊，" + data.get(0).getZhunbei() + "准备就诊");
//                            //创建Intent
//                            Intent intent = new Intent();
//                            intent.setAction("com.xzr.hospitalregister.broadcase.MyReceiver");
//                            intent.putExtra("text1", "请，" + data.get(0).getHujiao() + "到" + data.get(0).getZhenshi() + "就诊，" + data.get(0).getZhunbei() + "准备就诊");
//                            Log.e("TAG", "启动广播时要传入的值+++" + "请，" + data.get(0).getHujiao() + "到" + data.get(0).getZhenshi() + "就诊，" + data.get(0).getZhunbei() + "准备就诊");
////                                try {
////                                    Thread.currentThread().sleep(5000);//阻断2秒
////                                } catch (InterruptedException e) {
////                                    e.printStackTrace();
////                                }
//                                //发送广播
//                                sendBroadcast(intent);
                            }////////////////////////////////////////////////////////////////////////////
//                            Log.e("TAG","获取结束时间"+System.currentTimeMillis());
//                            data.clear();
                        }
//                            //////////
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

                default:
                    break;
            }
        }
    };
    /**
     * 播放音乐，参数是资源id
     *
     * @param MusicId
     */
    private void PlayMusic(int MusicId) {
        music = MediaPlayer.create(this, MusicId);
        music.start();
    }
    /////////////
    @Override
    public void onInit(int status) {
// TODO Auto-generated method stub
        //TTS Engine初始化完成
        if(status == TextToSpeech.SUCCESS)
        {
            int result = textToSpeech.setLanguage(Locale.US);
            //设置发音语言
            if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
            //判断语言是否可用
            {
                Log.v("TAG", "Language is not available");
//                speakBtn.setEnabled(false);
                textToSpeech.stop();//////////////////////////
            }
            else
            {
//                speakBtn.setEnabled(true);
                //设置一个语音片段结束后的回调函数
                textToSpeech.setOnUtteranceCompletedListener(this);
            }
        }
    }
    @Override
    public void onUtteranceCompleted(String utteranceId) {
// TODO Auto-generated method stub
        //一个语音片段结束后的回调函数
        Log.v("TAG", "Get completed message for the utteranceId " + utteranceId);
        //用lastUtterance记录当前结束的语音片段
        lastUtterance = Integer.parseInt(utteranceId);
    }
    private void speakText()
    {
        lastUtterance++;
        if(lastUtterance >= loveArray.length)
        {
            lastUtterance = 0;
        }
        Log.v("TAG", "the begin utterance is " + lastUtterance);
        for(int i = lastUtterance; i < loveArray.length; i++)
        {
            //为每个语音片段都设置一个标记
            params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, String.valueOf(i));
            textToSpeech.speak(loveArray[i], TextToSpeech.QUEUE_ADD, params);
        }
    }
    ///////////////
}
